package www.wen.com.common.lib.base

import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import www.wen.com.common.lib.data.entities.ItemIsSelected
import www.wen.com.common.lib.helper.SelectItemClickCallBack

/**
 * @author WEN
 * @Description:当item有单选事件时可以使用这个OnItemClickListener
 * @date 2021/11/8 13:05
 */
open class OnSelectItemClickListener<T:ItemIsSelected>(
        var currentPosition:Int = -1,
        private var resultCallBack: SelectItemClickCallBack<T>? = null,
        private var repeatCallBack: SelectItemClickCallBack<T>? = null,
        private val headCount:Int = 0
): OnItemClickListener {

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (currentPosition != position) {

            val currentEntity = (adapter.getItem(position)) as T
            currentEntity.isSelected = true

            if(currentPosition!=-1){
                val oldEntity = (adapter.getItem(currentPosition)) as T
                oldEntity.isSelected = false
                adapter.notifyItemChanged(currentPosition+headCount)
            }

            adapter.notifyItemChanged(position+headCount)

            currentPosition = position
            resultCallBack?.invoke(currentEntity,adapter,position)
        } else {
            repeatClick(adapter, position)
        }
    }

    /**
     * 重复点击同一个时的事件
     */
    private fun repeatClick(adapter: BaseQuickAdapter<*, *>,  position: Int) {
        val currentEntity = (adapter.getItem(position)) as T
        repeatCallBack?.invoke(currentEntity,adapter,position)
    }

}